package com.lishe.lishe.lishe.module.search.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayout;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerviewBaseAdapter;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.module.search.adapter.SearchInputConnectAdapter;
import com.lishe.lishe.lishe.module.search.bean.InputConnectBean;
import com.lishe.lishe.lishe.module.search.http.HttpSearch;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.scwang.smartrefresh.layout.util.DensityUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Bin
 * 搜索页
 */
public class HomeSearchActivity extends BaseActivity implements View.OnClickListener {

    public static final String SEARCH_FROM = "SEARCH_FROM";
    public static final String SEARCH_KEYWORD = "SEARCH_KEYWORD";

    private View mIvClear;
    private EditText mEditText;
    private RecyclerView mRecyclerView;
    private SearchInputConnectAdapter mAdapter;
    private List<String> mList = new ArrayList<>();
    private View mHistorylayout;
    private FlexboxLayout mFlexboxLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homesearch);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initHitstorys();
    }

    private void initHitstorys() {
        List<String> list = SharedPreferencesUtils.getSearchHitstory();
        if (list == null || "".equals(list.get(0))) {
            mHistorylayout.setVisibility(View.GONE);
        } else {
            mFlexboxLayout.removeAllViews();
            for (int i = 0; i < list.size(); i++) {
                mFlexboxLayout.addView(createItemView(list.get(i)));
            }
            mHistorylayout.setVisibility(View.VISIBLE);
        }
    }

    private TextView createItemView(final String text) {
        TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setText(text);
        textView.setTextSize(14);
        textView.setLines(1);
        textView.setHorizontallyScrolling(true);
        textView.setEllipsize(TextUtils.TruncateAt.END);
        textView.setTextColor(getResources().getColor(R.color.gray_9));
        textView.setBackgroundResource(R.drawable.bg_15dp_corner_999999_stroke);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferencesUtils.saveSearchHitstory(text);
                Intent i = new Intent(HomeSearchActivity.this, SearchResultActivity.class);
                i.putExtra(SEARCH_KEYWORD, text);
                i.putExtra(SEARCH_FROM, getIntent().getStringExtra(SEARCH_FROM));
                startActivity(i);

                mEditText.setText(text);
                mEditText.setSelection(text.length());
            }
        });
        int padding = DensityUtil.dp2px(5);
        int paddingLeftAndRight = DensityUtil.dp2px(10);
        ViewCompat.setPaddingRelative(textView, paddingLeftAndRight, padding, paddingLeftAndRight, padding);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        int marginLeft = DensityUtil.dp2px(0);
        int marginTop = DensityUtil.dp2px(0);
        int marginRight = DensityUtil.dp2px(10);
        int marginBottom = DensityUtil.dp2px(8);
        layoutParams.setMargins(marginLeft, marginTop, marginRight, marginBottom);
        textView.setLayoutParams(layoutParams);
        return textView;
    }

    private void initView() {
        mEditText = findViewById(R.id.edittext);
        String keyword = getIntent().getStringExtra(SEARCH_KEYWORD);
        if (keyword != null) {
            mEditText.setText(keyword);
            mEditText.setSelection(mEditText.getText().toString().length());
        }
        mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH){
                    String keyword = mEditText.getText().toString().trim();
                    if (TextUtils.isEmpty(keyword)) {
                        mEditText.getText().clear();
                        ToastUtil.showToast(HomeSearchActivity.this, "请输入您要搜索的商品!");
                        return true;
                    }
                    SharedPreferencesUtils.saveSearchHitstory(keyword);
                    Intent i = new Intent(HomeSearchActivity.this, SearchResultActivity.class);
                    i.putExtra(SEARCH_KEYWORD, mEditText.getText().toString());
                    i.putExtra(SEARCH_FROM, getIntent().getStringExtra(SEARCH_FROM));
                    startActivity(i);
                    return true;
                }
                return false;
            }
        });
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if ("".equals(mEditText.getText().toString())) {
                    mIvClear.setVisibility(View.GONE);
                    mList.clear();
                    mAdapter.notifyDataSetChanged();
                    mRecyclerView.setVisibility(View.GONE);
                    mHistorylayout.setVisibility(View.VISIBLE);
                } else {
                    mRecyclerView.setVisibility(View.VISIBLE);
                    mHistorylayout.setVisibility(View.GONE);
                    mIvClear.setVisibility(View.VISIBLE);
                    getInputConnect(mEditText.getText().toString());
                }
            }
        });

        mIvClear = findViewById(R.id.clear);
        mIvClear.setOnClickListener(this);
        mHistorylayout = findViewById(R.id.historylayout);
        mFlexboxLayout = findViewById(R.id.FlexboxLayout);

        mRecyclerView = findViewById(R.id.recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new SearchInputConnectAdapter(HomeSearchActivity.this, mList);
        mAdapter.setOnItemClickListener(new RecyclerviewBaseAdapter.ItemListener.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                mEditText.setText(mList.get(position));
                mEditText.setSelection(mEditText.getText().toString().length());
                SharedPreferencesUtils.saveSearchHitstory(mList.get(position));
                Intent i = new Intent(HomeSearchActivity.this, SearchResultActivity.class);
                i.putExtra(SEARCH_KEYWORD, mList.get(position));
                i.putExtra(SEARCH_FROM, getIntent().getStringExtra(SEARCH_FROM));
                startActivity(i);
            }
        });
        mRecyclerView.setAdapter(mAdapter);

        findViewById(R.id.cancel).setOnClickListener(this);
        findViewById(R.id.history_clear).setOnClickListener(this);
    }

    /**
     * 根据输入的内容自动联想补全
     * @param keyword
     */
    private void getInputConnect(String keyword) {
        HttpSearch.getInputConnect(keyword, new DataResponseListener<InputConnectBean>() {
            @Override
            public void onSuccess(InputConnectBean bean) {
                mList.clear();
                mList.addAll(bean.getData());
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFail(String failMessage) {}

            @Override
            public void onError(Throwable e) {}
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cancel:
                finish();
                break;
            case R.id.clear:
                mEditText.getText().clear();
                break;
            case R.id.history_clear:
                SharedPreferencesUtils.clearSearchHitstory();
                initHitstorys();
                break;
        }
    }
}
